using System;
using System.Collections;
using System.Collections.Generic;
using MyFrame.Pool;
using UnityEngine;
using Plugin.Tool;

namespace Platform.Skill.Deployer
{
    public enum SwordType
    {
        Regular,
        Bounce,
        Pierce,
        Spin,
    }

    /// <summary>
    /// 抛剑 释放器 
    /// </summary>
    public class ThrowSwordSkillDeployer : ParabolicSkillDeployer
    {
        private float returnSpeed = 20;
        public bool isReturning;
        /// <summary>
        /// 能够转向
        /// </summary>
        public bool canRotate = true;

        void Update()
        {
            if (canRotate)
                transform.right = -rb.velocity;

            if (isReturning)
            {
                transform.position = Vector2.MoveTowards(transform.position
                , player.transform.position, returnSpeed * Time.deltaTime);

                var distance = Vector2.Distance(transform.position, player.transform.position);
                if (distance < 0.1f)
                {
                    player.ChangeState(Entity.States.CatchSword);
                    DestroySword();
                }
            }
        }
        void DestroySword()
        {
            isReturning = false;
            if (player.sword = null) return;
            //再次关闭效果
            // EndEffect();  
            player.sword = null;
            // 回收预制体
            PoolMgr.Instance.Release(skillData.skillPrefab);
        }


        protected override void OnTriggerEnter2D(Collider2D other)
        {
            if (isReturning) return;
            base.OnTriggerEnter2D(other);
        }


        public override void DeploySkill()
        {
            base.DeploySkill();
            canRotate = true;
            isReturning = false;
            player.sword = gameObject;

            // 距离过远超过时间自动销毁
            // 创建太快多次调用会 有重复销毁bug
            ZTimer.ClearTimer(DestroySwordByDistance);
            ZTimer.SetTimeout(5f, DestroySwordByDistance);
        }

        private void DestroySwordByDistance()
        {
            var distance = Vector2.Distance(transform.position, player.transform.position);
            if (distance > 15f)
            {
                DestroySword();
            }
        }

        public override void EndEffect()
        {
            ZTimer.ClearTimer(DestroySwordByDistance);
            base.EndEffect();
        }

        /// <summary>
        /// 返回剑
        /// </summary>
        public override void ReturnSword()
        {
            // deployer.rb.isKinematic = false;//受物理控制
            rb.constraints = RigidbodyConstraints2D.FreezeAll;
            transform.parent = null;
            isReturning = true;
        }

        public override void SetRotate(bool value)
        {
            base.SetRotate(value);
            canRotate = value;
        }


        public override void StopRigidbody()
        {
            base.StopRigidbody();
            canRotate = false;
        }
    }
}